package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	adminController "goapi/admin/controller"
	middleware "goapi/middlewares"
	"net/http"
	"time"
)

func InitRouter(g *gin.Engine, m ...gin.HandlerFunc) *gin.Engine {
	// 格式化日志输出格式
	g.Use(gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string {
		return fmt.Sprintf(
			"%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			params.ClientIP,
			params.TimeStamp.Format(time.RFC1123),
			params.Method,
			params.Path,
			params.Request.Proto,
			params.StatusCode,
			params.Latency,
			params.Request.UserAgent(),
			params.ErrorMessage,
		)
	}))

	g.Use(gin.Recovery())
	g.Use(m...)

	g.NoRoute(func(c *gin.Context) {
		c.String(http.StatusNotFound, "The router is not exist!")
	})

	r := g.Group("/api")
	{
		r.GET("/captcha", adminController.GetCaptch)
		admin := r.Group("/admin", middleware.AdminAuth())
		{
			admin.POST("/login", adminController.Login)
			manager := admin.Group("/manager")
			{
				manager.POST("/list", adminController.ManagerList)
				manager.POST("/addOrUpdate", adminController.ManagerAddOrUpdate)
				manager.POST("/info", adminController.ManagerInfo)
				manager.POST("/del", adminController.ManagerDel)
			}
		}
	}

	return g

}
